function labelIdx = getBalancedTrainset(L,m,method)
% labelIdx = getBalancedTrainset(L)
% L - labels different from zero
% m (optional) maximum number of samples per class
% method (optional) - 'rand'=random deselection (default) 
%          'leading' - deselect leading
%          'tail' - deselect tail 
%          'equal'- deselect uniformly (1:x:N);
% returns binary vector labelIdx of size(L)

classes = setdiff(unique(L),0); % ignore zero labels
nClasses=length(classes);
NLabel = zeros(1,nClasses);

idx=cell(1,nClasses);
for k=1:nClasses,
    idx{k}=find(L==classes(k));
    NLabel(k)=length(idx{k});
end

[n minCond]=sort(NLabel);
if nargin>1 && ~isempty(m) && m>0,
    n(1)=min(n(1),m);
end
if nargin<3,
    method='rand';
end

for k=1:length(n),
    if strcmpi(method,'rand'),
        randIdx=randperm(NLabel(minCond(k)));
        L(idx{minCond(k)}(setdiff(1:NLabel(minCond(k)),randIdx(1:n(1)))))=0;
    elseif strcmpi(method,'tail'),
        L(idx{minCond(k)}(n(1)+1:NLabel(minCond(k))))=0;
    elseif strcmpi(method,'leading'),
        L(idx{minCond(k)}(1:NLabel(minCond(k))-n(1)))=0;
    elseif strcmpi(method,'equal'),
        NRemove=NLabel(minCond(k))-n(1);
        stepSize=NLabel(minCond(k))/(NRemove+1);
        removeIdx = round(stepSize:stepSize:NLabel(minCond(k))-stepSize);
        L(idx{minCond(k)}(removeIdx))=0;
    end
end
labelIdx=L~=0;
